package com.itboye.sunsun.buy.ui;

import java.security.acl.Owner;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.itboye.sunsun.R;
import com.itboye.sunsun.beans.RedPacketBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.shop.ui.AllShopActivity;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.DoubleParse;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class RedPacketActivity extends BaseActivity implements OnClickListener {

	ViewGroup container;

	private ImageView back;
	double price;
	ArrayList<View> views;
	ArrayList<View> viewsGuoqi;
	ArrayList<View> viewNormal;
	private String type;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_red_packet_select);
		price = getIntent().getDoubleExtra("price", 0);
			
			type = getIntent().getStringExtra("type");
		views = new ArrayList<View>();
		viewsGuoqi = new ArrayList<>();
		viewNormal = new ArrayList<View>();
		getData();

	}

	private void getData() {

		MyJsonRequest<List<RedPacketBean>> request = new MyJsonRequest.Builder<List<RedPacketBean>>()
				.apiVer("100")
				.typeKey("BY_RedEnvelope_query")
				.param("uid",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.requestListener(new XRequestListener<List<RedPacketBean>>() {

					@Override
					public void onResponse(List<RedPacketBean> arg0) {
						for (final RedPacketBean redPacketBean : arg0) {
							View v = LayoutInflater.from(
									getApplicationContext()).inflate(
									R.layout.item_red_packet, container, false);
							((TextView) v.findViewById(R.id.money))
									.setText(redPacketBean.getMoney());
							((TextView) v.findViewById(R.id.xianzhi))
									.setText("满"+redPacketBean.getUseCondition()+"元可用");
							((TextView) v.findViewById(R.id.desc))
									.setText(redPacketBean.getName());
							long time = Long.parseLong(redPacketBean
									.getGetTime())
									* 1000
									+ Long.parseLong(redPacketBean
											.getExpireTime()) * 1000;
							long nowTime = new Date().getTime();
							if (Integer.parseInt(redPacketBean.getUseStatus()) == 0) {
								((TextView) v.findViewById(R.id.money))
										.setTextColor(Color.RED);
								((TextView) v.findViewById(R.id.day))
										.setTextColor(Color.RED);
								((ImageView) v.findViewById(R.id.img_usestate))
										.setBackgroundResource(R.drawable.line_red);
								((TextView) v.findViewById(R.id.day))
										.setText(time > nowTime ? ("还有"
												+ getDays(
														new java.text.SimpleDateFormat(
																"yyyy-MM-dd",
																Locale.CHINA)
																.format(Long
																		.parseLong(redPacketBean
																				.getGetTime())
																		* 1000
																		+ Long.parseLong(redPacketBean
																				.getExpireTime())
																		* 1000),
														new java.text.SimpleDateFormat(
																"yyyy-MM-dd",
																Locale.CHINA).format(System
																.currentTimeMillis())) + "天过期")
												: "已经过期");
							} else {
								((TextView) v.findViewById(R.id.money))
										.setTextColor(Color.GRAY);
								((TextView) v.findViewById(R.id.day))
										.setTextColor(Color.GRAY);
								((TextView) v.findViewById(R.id.day))
										.setText("已使用");
								((ImageView) v.findViewById(R.id.img_usestate))
										.setBackgroundResource(R.drawable.line_gray);
							}
							((TextView) v.findViewById(R.id.menkan))
									.setText(redPacketBean.getNotes());
							int t = (int) DoubleParse.parse(
									redPacketBean.getExpireTime(), 0);// 过期的时间
							// 一天=86400秒
							if (time < nowTime) {
								((TextView) v.findViewById(R.id.money))
										.setTextColor(Color.GRAY);
								((TextView) v.findViewById(R.id.day))
										.setTextColor(Color.GRAY);
								((ImageView) v.findViewById(R.id.img_usestate))
										.setBackgroundResource(R.drawable.line_gray);

							}

							Calendar rightNow = Calendar.getInstance();
							rightNow.add(Calendar.SECOND, t);
							String end = new java.text.SimpleDateFormat(
									"yyyy-MM-dd", Locale.CHINA).format(rightNow
									.getTime());

							((TextView) v.findViewById(R.id.endTime)).setText("有效期至："
									+ new java.text.SimpleDateFormat(
											"yyyy-MM-dd", Locale.CHINA).format(Long
											.parseLong(redPacketBean
													.getGetTime())
											* 1000
											+ Long.parseLong(redPacketBean
													.getExpireTime()) * 1000));

							System.out.println("(getUseStatus:"+redPacketBean.getUseStatus()+")(getUseCondition:"+redPacketBean.getUseCondition()+")(price"+price);
							if ("0".equals(redPacketBean.getUseStatus())
									&&time >= nowTime) {
//								viewNormal.add(v);
								// DoubleParse.parse(redPacketBean.getUseCondition(), 0) <= price&& 
								container.addView(v, 0);
								v.setOnClickListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
										
										if (type != null) {
											Toast.makeText(RedPacketActivity.this, "请在购物下单时使用本红包", 0).show();
											Intent intent=new Intent(RedPacketActivity.this,AllShopActivity.class);
											startActivity(intent);
											return;
										}
										if(DoubleParse.parse(redPacketBean.getUseCondition(), 0) > price){
											Toast.makeText(RedPacketActivity.this, "你的金额未达到优惠金额，无法使用该红包", 0).show();
											return;
										}
										Intent intent = new Intent();
										intent.putExtra("id",
												redPacketBean.getId());
										if (price <= DoubleParse.parse(
												redPacketBean.getMoney(), 0)) {
											intent.putExtra("price",
													(price - 0.01) + "");
										} else {
											intent.putExtra(
													"price",
													((TextView) v
															.findViewById(R.id.money))
															.getText()
															.toString());
										}
										setResult(RESULT_OK, intent);
										finish();
									}
								});
							} else {
								if (time < nowTime) {
									viewsGuoqi.add(v);
									v.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											Toast.makeText(
													RedPacketActivity.this,
													"红包已过期,无法使用", 0).show();
										}
									});
								} else {
									views.add(v);
									v.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											Toast.makeText(
													RedPacketActivity.this,
													"红包已经使用过,无法再次使用", 0).show();
										}
									});
								}
								v.setEnabled(true);
								// setEnable(v);
							}

						}
						for (int i = 0; i < views.size(); i++) {
							container.addView(views.get(i));
						}
						for (int i = 0; i < viewsGuoqi.size(); i++) {
							System.out.println(">>>>" + "执行le" + i);
							container.addView(viewsGuoqi.get(i));
						}
					}

				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	private void setEnable(View v) {
		if (v instanceof TextView) {
			((TextView) v).setTextColor(Color.GRAY);
			return;
		}
		if (v instanceof ViewGroup) {
			ViewGroup vg = (ViewGroup) v;
			for (int i = vg.getChildCount() - 1; i > -1; i--) {
				setEnable(vg.getChildAt(i));
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.back) {
			finish();
		}

	}

	public int getDays(String time1, String time2) {
		int days = 0;
		try {
			// 时间转换类
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = sdf.parse(time1);
			Date date2 = sdf.parse(time2);
			// 将转换的两个时间对象转换成Calendard对象
			Calendar can1 = Calendar.getInstance();
			can1.setTime(date1);
			Calendar can2 = Calendar.getInstance();
			can2.setTime(date2);
			// 拿出两个年份
			int year1 = can1.get(Calendar.YEAR);
			int year2 = can2.get(Calendar.YEAR);
			// 天数
			days = 0;
			Calendar can = null;
			// 如果can1 < can2
			// 减去小的时间在这一年已经过了的天数
			// 加上大的时间已过的天数
			if (can1.before(can2)) {
				days -= can1.get(Calendar.DAY_OF_YEAR);
				days += can2.get(Calendar.DAY_OF_YEAR);
				can = can1;
			} else {
				days -= can2.get(Calendar.DAY_OF_YEAR);
				days += can1.get(Calendar.DAY_OF_YEAR);
				can = can2;
			}
			for (int i = 0; i < Math.abs(year2 - year1); i++) {
				// 获取小的时间当前年的总天数
				days += can.getActualMaximum(Calendar.DAY_OF_YEAR);
				// 再计算下一年。
				can.add(Calendar.YEAR, 1);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return days;
	}
}
